<template>
  <view class="auth-box"></view>
</template>

<script>
  import qs from '@/utils/qs.js'
  import {platformMap}  from '@/common/models.js'
  
  export default {
    data() {
      return {
        reURL: '',
        vid: 0,
        mid: 0,
        loginBy: '',
        loginState: '',
        fbCode: ''
      }
    },
    onLoad(e) {
      if (e.reurl) {
        this.reURL = e.reurl
      }
      if (e.vid) {
        this.vid = e.vid
        this.mid = e.mid
      }
      this.loginBy = e.loginby || 'fb'
      uni.showLoading({
        title: '登录授权中' // todo
      })
        
      if (e.code && e.state && this.loginBy == 'fb') {
        this.loginState = e.state
        this.fbCode = e.code
        this.fbLoginByCode()
      }
      
      
      if (location.hash != '') {
        let hash = location.hash.slice(1);
        let params = hash.split('&');
        let auth = {};
        params.forEach(param => {
          let [key, val] = param.split('=');
          auth[key] = val; 
        })
        
        if (auth.access_token) {
          this.login('google', auth.access_token)
          this.loginState = auth.state
          
          console.log({auth})
        }
      }
    },
    methods: {
      login (platfrom, accessToken) {
        console.log('get', platformMap.get(platfrom))
        const that = this
        if (accessToken) {
          let requestData = {
            vid: that.vid,
            mid: that.mid,
            token: accessToken
          }
          if (uni.getStorageSync('userFrom')) {
            requestData.source = uni.getStorageSync('userFrom')
          }
          if (uni.getStorageSync('guestId')) {
            requestData['guest_id'] = uni.getStorageSync('guestId')
          }
          uni.request({
            url: this.configs.apiUrl + '/api/user/' + platfrom,
            data: requestData,
            success(res) {
              that.handleLoginSuccess(res, platfrom);
            }
          })
        }
      },
      fbLoginByCode () {
        const that = this
        const paramsObj = qs.parse(that.loginState);
        let locationUrl = this.configs.webUrl + '/pages/auth?loginby=fb';
        // let locationUrl = 'https://localhost:9999/h5/pages/auth?loginby=fb';
        // 从state取出vid，mid
        let requestData = {
          code: that.fbCode,
          url: locationUrl
        }
          
        if (paramsObj.vid) {
          requestData.vid = paramsObj.vid
          that.vid = paramsObj.vid
        }
        if (paramsObj.mid) {
          that.mid = paramsObj.mid
        }
        
        if (uni.getStorageSync('userFrom')) {
          requestData.source = uni.getStorageSync('userFrom')
        }
        if (uni.getStorageSync('guestId')) {
          requestData['guest_id'] = uni.getStorageSync('guestId')
        }
        uni.request({
          url: this.configs.apiUrl + '/api/user/facebook',
          data: requestData,
          success(res) {
            that.handleLoginSuccess(res, 'facebook');
          }
        })
      },
      handleLoginSuccess (res, platfrom, isByCode) {
        const that = this
        if(res.data.code === 1){
          uni.showToast({ title: that.$t('login.success'), icon:"success" });
          var avatar='';
          if(res.data.data.userinfo.avatar){
        		var str = res.data.data.userinfo.avatar;
        		if(str.indexOf("data:image") == -1){
        			if(str.indexOf("http") != -1){
        				avatar=res.data.data.userinfo.avatar;
        			}else{
        				avatar=that.configs.imgUrl+res.data.data.userinfo.avatar;
        			}
        		}
        	}
          uni.setStorage({//快取配置資訊
            key: 'avatar',  
            data: avatar
          })
          uni.setStorage({//快取配置資訊
            key: 'userinfo',  
            data: res.data.data.userinfo
          })
          uni.setStorage({//快取配置資訊
            key: 'config',  
            data: res.data.data.config
          })
          
          // 1,fb;2,gg;3,titkok,4,account
          that.GAHandle('login',  platformMap.get(platfrom), {
            'code': platfrom,
            mid: that.mid,
            vid: that.vid
          })
          
            
          if (that.reURL) {
            location.href = that.reURL
          } else if (that.vid) {
            uni.reLaunch({
              url: `/pages/client/tuan/detail?vid=${that.vid}&mid=${that.mid}`
            })
          } else if (platfrom == 'google' && that.loginState != 'loginpage') {
            uni.reLaunch({
              url: decodeURIComponent(that.loginState)
            })
          } else {
            const pages = getCurrentPages()
            // console.log({pages}, pages.length)
            if (pages.length == 1) {
              uni.reLaunch({
                url: '/pages/client/index'
              })
            } else {
              uni.navigateBack()
            }
          }
        } else {
          
          uni.showToast({ title: res.data.msg || this.$t('login.failed'), icon:"none", complete: ()=> {
            uni.redirectTo({
              url:'/pages/login/login'
            })
          } });
        }
      },
    }
  }
</script>

<style>
  .auth-box {
    display: flex;
    align-items: center;
    height: 100vh;
    width: 100vw;
    justify-content: center;
  }
  .button-login {
    width: 654rpx;
    height: 98rpx;
    box-shadow: 0rpx 0rpx 13rpx 0rpx rgba(164, 217, 228, 0.2);
    background-size: contain;
  }
  .button-login-fb {
    background-image: url(../static/img/login/login_fb.png);
  }
</style>